#include <stdio.h>
#include <unistd.h>
#include <ctime>
#include <iostream>
#include <sstream>
#include <locale>
#include <pthread.h>
#include <time.h>
#include <iomanip>
#include "date.h"

using namespace std;

int step = 100;
struct tm *info;
int buffSize = 60;

void forDateString(time_t now, string &result)
{
    char buffer[buffSize];
    info = localtime(&now);
    strftime(buffer, buffSize, "%Y-%m-%d %H:%M:%S %A", info);
    result.assign(buffer);
}

void formatDate(time_t now, char *buffer, int buffsize)
{
    info = localtime(&now);
    strftime(buffer, buffSize, "%Y-%m-%d %H:%M:%S %A", info);
}

string forDateString(time_t now)
{
    char buffer[buffSize];
    info = localtime(&now);
    strftime(buffer, buffSize, "%Y-%m-%d %H:%M:%S %A", info);
    return string(buffer);
}

void outputDate(void)
{
    time_t now = time(0);
    char *dt = ctime(&now);
    cout << "本地日期和时间 : " << dt << endl;

    char dateFormatResult[buffSize];
    formatDate(now, dateFormatResult, buffSize);
    cout << "本地日期和时间：" << dateFormatResult << endl;

    string dateResult = forDateString(now);
    const char *result = dateResult.c_str();

    cout << "本地日期和时间：" << result << endl;
    string newResult;
    forDateString(now, newResult);
    cout << "本地日期和时间：" << newResult << endl;
}

int main(int argc, char const *argv[])
{
    pthread_t pd1, pd2;
    int error;

    // error = pthread_create(&pd1, NULL, thread1, NULL);
    // if (error)
    // {
    //     printf("创建线程1失败：%d\n", error);
    // }

    // error = pthread_create(&pd2, NULL, thread2, NULL);
    // if (error)
    // {
    //     printf("创建线程2失败：%d\n", error);
    // }

    // pthread_join(pd1, NULL);
    // pthread_join(pd2, NULL);
    {
        long long int nanos_to_seconds = 1000000000; // conversion factor
        long long int nanos_to_milis = 1000000;
        time_t now = time(NULL);
        long long int ts = 8137140505904;//1561402947698860015;

        time_t t = static_cast<time_t>(ts / nanos_to_seconds);
        //^ change here
        long long int milis = ts % nanos_to_seconds / nanos_to_milis; // compute milliseconds
        std::cout << std::asctime(std::localtime(&t))
                  << t << "." << std::setfill('0') << std::setw(3) << milis
                  << " seconds since the Epoch\n";
        std::cout << "done" << std::endl;
        return 0;
    }
}

// void *thread1(void *param)
// {
//     for (int i = 0; i < step; i++)
//     {
//         sleep(1);
//         outputDate();
//     }
// }

// void *thread2(void *param)
// {
//     int i;
//     for (i = 0; i < step; i++)
//     {
//         usleep(1000000); // 休眠 1s
//         printf("%s: %d: thread2: %d\n", __FILE__, __LINE__, i);
//     }
// }

//g++ date.cpp  -o main -lpthread && ./main